<template>
  <el-card class="container-card hidden-scrollbar">
    <template #header>
      <div class="card-header">
        <span class="header-title">住宿订单 - 住宿记录</span>
      </div>
    </template>

    <div class="content-wrapper">
      <!-- 筛选卡片 -->
      <el-card class="filter-card">
        <div class="filter-section">
          <span class="section-title">快速筛选</span>
          <div class="button-group">
            <el-button type="primary" plain>今日预抵列表</el-button>
            <el-button type="success" plain>今日预离列表</el-button>
            <el-button type="warning" plain>今日抵店列表</el-button>
            <el-button type="danger" plain>今日离店列表</el-button>
          </div>
        </div>

        <el-divider class="custom-divider" />

        <div class="filter-section">
          <span class="section-title">住宿状态</span>
          <div class="button-group">
            <el-button 
              v-for="(btn, index) in statusButtons" 
              :key="index" 
              :type="btn.type" 
              plain
            >
              {{ btn.label }}
            </el-button>
          </div>
        </div>

        <!-- 搜索区域 -->
        <div class="search-area">
          <el-form :model="searchForm" class="search-form">
            <div class="search-group">
              <el-select
                v-model="searchForm.guestType"
                placeholder="房客姓名"
                class="search-select"
              >
                <el-option
                  v-for="item in guestOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-input
                v-model="searchForm.keyword"
                placeholder="请输入查询关键字"
                class="search-input"
                clearable
              />
              <el-button type="primary" icon="Search" @click="handleSearch" />
            </div>

            <el-button type="info" class="export-btn">
              <i class="el-icon-download"></i>
              导出明细
            </el-button>

            <div class="search-group">
              <el-select
                v-model="searchForm.timeType"
                placeholder="下单时间"
                class="time-select"
              >
                <el-option
                  v-for="item in timeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="date-picker"
                value-format="yyyy-MM-dd"
              />
            </div>
          </el-form>
        </div>
      </el-card>

      <!-- 数据表格 -->
      <el-card class="table-card">
        <el-table 
          :data="paginatedData" 
          stripe 
          v-loading="loading"
          height="calc(60vh - 50px)"
        >
          <el-table-column prop="roomNum" label="房号" width="100" />
          <el-table-column prop="roomTypeName" label="房型" width="120" />
          <el-table-column prop="orderSource" label="状态" width="100">
            <template #default="{row}">
              <el-tag :type="statusTagMap[row.orderSource]">
                {{ row.orderSource }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="reservationName" label="客人姓名" width="120" />
          <el-table-column prop="checkInTime" label="(预)抵店时间" width="180">
            <template #default="{row}">
              {{ formatTime(row.checkInTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="checkOutTime" label="(预)离店时间" width="180">
            <template #default="{row}">
              {{ formatTime(row.checkOutTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="sourceInformation" label="客户类型" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{row}">
              <el-button 
                type="text" 
                size="small"
                @click="AlipayPay(row)"
              >
                <i class="el-icon-wallet"></i>
                付款
              </el-button>
              <el-divider direction="vertical" />
              <el-button 
                type="text" 
                size="small"
                @click="handleOperation(row)"
              >
                操作
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalItems"
          />
        </div>
      </el-card>
    </div>
  </el-card>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { GetStayRecord } from '@/api/index'
import { AlipayPagePay } from '@/api/AlipaySandbox/AlipayIndex'
import { ElMessage } from 'element-plus'
import moment from 'moment'
import SnowflakeId from 'snowflake-id'

// 雪花ID生成器
const snowflake = new SnowflakeId()

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const allTableData = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  guestType: '1',
  keyword: '',
  timeType: '1',
  dateRange: []
})

// 状态标签映射
const statusTagMap = reactive({
  '已结算': 'success',
  '待入住': 'warning',
  '已取消': 'danger',
  '入住中': 'primary',
  '已退房': 'info'
})

// 状态按钮配置
const statusButtons = reactive([
  { label: '全部', type: '' },
  { label: '待入住', type: 'warning' },
  { label: '入住中', type: 'primary' },
  { label: '已退房', type: 'info' },
  { label: '已结算', type: 'success' },
  { label: '超时未入住', type: 'danger' },
  { label: '已取消', type: 'danger' }
])

// 选项配置
const guestOptions = reactive([
  { value: '1', label: '房客姓名' },
  { value: '2', label: '证件号' },
  { value: '3', label: '手机号' },
  { value: '4', label: '房号' }
])

const timeOptions = reactive([
  { value: '1', label: '下单时间' },
  { value: '2', label: '入住时间' },
  { value: '3', label: '离店时间' }
])

// 计算属性
const totalItems = computed(() => allTableData.value.length)
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allTableData.value.slice(start, end)
})

// 支付宝支付
const AlipayPay = (rowdata) => {
  try {
    const paymentData = {
      OutTradeNo: snowflake.generate(),
      Subject: "住宿订单",
      Body: "请支付订单金额",
      TotalAmount: rowdata.totalPrices,
      NotifyUrl: "http://a7wt8g.natappfree.cc/PagePayNotify",
      ReturnUrl: "http://localhost:5173/Order/AccommodationOrders/AccommodationRecords",
    }

    AlipayPagePay(paymentData).then(res => {
      const payWindow = window.open('', '_blank')
      payWindow.document.write(res)
      ElMessage.success('支付页面已打开，请完成支付')
    }).catch(error => {
      console.error('支付请求失败:', error)
      ElMessage.error('支付发起失败')
    })
  } catch (error) {
    console.error('支付异常:', error)
    ElMessage.error('支付处理出现异常')
  }
}

// 获取数据
const getTableData = async () => {
  try {
    loading.value = true
    const res = await GetStayRecord()
    if (res.code === 200) {
      allTableData.value = res.data || []
    } else {
      ElMessage.error(res.message || '数据获取失败')
    }
  } catch (error) {
    console.error('请求异常:', error)
    ElMessage.error('服务器连接失败')
  } finally {
    loading.value = false
  }
}

// 时间格式化
const formatTime = (time) => {
  return moment(time).format("YYYY-MM-DD HH:mm")
}

// 操作处理
const handleOperation = (row) => {
  console.log('操作数据:', row)
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}

// 初始化加载
onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.container-card {
  width: 100%;
  min-height: 100vh;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  padding: 18px 20px;
  border-bottom: 1px solid #ebeef5;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.filter-card {
  margin-bottom: 15px;
  border-radius: 6px;
}

.filter-section {
  display: flex;
  align-items: center;
  margin: 12px 0;
}

.section-title {
  font-size: 14px;
  color: #606266;
  min-width: 80px;
}

.button-group {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.search-area {
  margin-top: 15px;
}

.search-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.search-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-select {
  width: 110px;
}

.search-input {
  width: 240px;
}

.date-picker {
  width: 240px;
}

.export-btn {
  margin: 0 20px;
}

.table-card {
  margin-top: 15px;
  border-radius: 6px;
}

.pagination-wrapper {
  padding: 20px 0;
  display: flex;
  justify-content: flex-end;
  background: #fff;
}

.el-button [class*=el-icon-]+span {
  margin-left: 4px;
}

.custom-divider {
  margin: 16px 0;
}
</style>